package com.gitee.ayezs.util;

import com.gitee.ayezs.annotation.wrapper.WrapperAnnotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class AnnotationUtil {
    public static <A extends Annotation> List<FindAnnotationInfo> findWrapperAnnotation(Field field) {
        if (field == null) {
            return null;
        }
        List<FindAnnotationInfo> findAnnotationInfos = new ArrayList<>();
        for (Annotation annotation : field.getAnnotations()) {
            //跳过java自带的注解
            if(isJavaAnnotations(annotation)){
                continue;
            }

            FindAnnotationInfo findAnnotationInfo = findWrapperAnnotation(annotation.annotationType());
            if(findAnnotationInfo != null){
                findAnnotationInfo.setCondition(annotation);

                InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
                try {
                    Field f = invocationHandler.getClass().getDeclaredField("memberValues");
                    f.setAccessible(true);
                    Map<String, Object> memberValues = (Map<String, Object>) f.get(invocationHandler);
                    Object group = memberValues.get("group");
                    if(group instanceof Class[]){
                        findAnnotationInfo.setGroup((Class[]) group);
                    }
                } catch (NoSuchFieldException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
                findAnnotationInfos.add(findAnnotationInfo);
            }
        }
        return findAnnotationInfos;
    }

    public static <A extends Annotation> FindAnnotationInfo findWrapperAnnotation(Class<A> clazz) {
        if (clazz == null) {
            return null;
        }
        for (Annotation annotation : clazz.getAnnotations()) {
            if(isJavaAnnotations(annotation)){
                continue;
            }
            if(annotation instanceof WrapperAnnotation){
                FindAnnotationInfo findAnnotations = new FindAnnotationInfo();
                findAnnotations.setWrapperAnnotation((WrapperAnnotation) annotation);
                return findAnnotations;
            } else {
                FindAnnotationInfo findAnnotations = findWrapperAnnotation(annotation.annotationType());
                if(findAnnotations != null){
                    findAnnotations.setCondition(annotation);
                    return findAnnotations;
                }
            }
        }
        return null;
    }

    /**
     * 只有java自带的注解
     */
    private static boolean isJavaAnnotations(Annotation type) {
        return type.annotationType().getName().startsWith("java.");
    }

}
